<?php

// 查立得PHP+mysql通用预约排队系统 V2024.12.12
// 演示地址: http://duilie.chalide.cn
// 文件路径: dengji.php
// 文件大小: 10912 字节
// 最后修改时间: 2024-12-17 21:00:00
// 作者: yujianyue
// 邮件: 15058593138@qq.com
// 版权所有,保留发行权和署名权
define('IN_SYSTEM', true);
require_once 'inc/conn.php';
require_once 'inc/pubs.php';
require_once 'inc/json.php';

// 获取参数
$doctor_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$timestamp = isset($_GET['t']) ? intval($_GET['t']) : 0;
$doctor_id = isset($_POST['id']) ? intval($_POST['id']) : $doctor_id;
// 验证医生ID
$sql = "SELECT id, name, department, status, end_time FROM doctor WHERE id = $doctor_id";
$doctor = $conn->query($sql)->fetch_assoc();

if(!$doctor) {
   json_msg(0, '直接访问无效');
}

// 处理AJAX请求
if(isset($_GET['act'])) {
    switch($_GET['act']) {
        case 'check':
            checkStatus($doctor, $timestamp);
            break;
        case 'submit':
            submitBooking($doctor);
            break;
        case 'count':
            getWaitingCount($doctor);
            break;
        default:
            json_msg(0, '未知操作');
    }
    exit;
}

// 检查状态
function checkStatus($doctor, $timestamp) {
    global $CONFIG;
    
    // 检查二维码时效
    if(time() - $timestamp > $CONFIG['qrcode_expire']) {
        json_msg(0, '二维码已过期，请重新扫码');
    }
    
    // 检查医生状态
    if($doctor['status'] != 1) {
        json_msg(0, '暂停预约');
    }
    
    // 检查结束时间
    if($doctor['end_time'] && strtotime($doctor['end_time']) < time()) {
        json_msg(0, '已结束预约');
    }
    
    json_msg(1, 'success');
}

// 提交预约
function submitBooking($doctor) {
    global $conn, $CONFIG;
    
    // 获取POST数据
    $name = isset($_POST['name']) ? safe_string($_POST['name']) : '';
    $mobile = isset($_POST['mobile']) ? safe_string($_POST['mobile']) : '';
    $id_card = isset($_POST['id_card']) ? safe_string($_POST['id_card']) : '';
    
    // 验证数据
    if(empty($name) || empty($mobile)) {
        json_msg(0, '请填写姓名和手机号');
    }
    
    if(!check_mobile($mobile)) {
        json_msg(0, '手机号格式错误');
    }
    
    if($CONFIG['id_card_required'] && !check_id_card($id_card)) {
        json_msg(0, '身份证号格式错误');
    }
    
    $today = date('Y-m-d');
    $sql = "SELECT id FROM booking 
            WHERE mobile = '$mobile' 
            AND booking_date = '$today' 
            AND status = 0";
    if($conn->query($sql)->num_rows > 0) {
        json_msg(0, '您今天已经预约过了');
    }
  
    // 生成顺序号
    $sql = "SELECT MAX(CAST(sequence AS UNSIGNED)) as max_seq FROM booking 
            WHERE doctor_id = {$doctor['id']} AND booking_date = '$today'";
    $result = $conn->query($sql)->fetch_assoc(); //问题出
    $sequence = sprintf("%04d", intval($result['max_seq']) + 1);
    
    // 生成核销码
    $verify_code = generate_verify_code();
    
    // 写入数据库
    $sql = "INSERT INTO booking (
                doctor_id, department, doctor_name, 
                booking_date, booking_time,
                patient_name, mobile, id_card,
                sequence, verify_code
            ) VALUES (
                {$doctor['id']}, '{$doctor['department']}', '{$doctor['name']}',
                '$today', NOW(),
                '$name', '$mobile', '$id_card',
                '$sequence', '$verify_code'
            )";
            
    if($conn->query($sql)) {
        // 获取未核销人数
        $sql = "SELECT COUNT(*) as count 
                FROM booking 
                WHERE doctor_id = {$doctor['id']} 
                AND booking_date = '$today' 
                AND status = 0";
        $waiting = $conn->query($sql)->fetch_assoc()['count'];
        
        json_msg(1, '预约成功', array(
            'sequence' => $sequence,
            'verify_code' => $verify_code,
            'waiting' => $waiting,
            'time' => date('Y-m-d H:i:s')
        ));
    } else {
        json_msg(0, '系统错误，请重试');
    }
}

// 获取等待人数
function getWaitingCount($doctor) {
    global $conn;
    
    $today = date('Y-m-d');
    $sql = "SELECT COUNT(*) as count 
            FROM booking 
            WHERE doctor_id = {$doctor['id']} 
            AND booking_date = '$today' 
            AND status = 0";
    $waiting = $conn->query($sql)->fetch_assoc()['count'];
    
    json_msg(1, 'success', array('count' => $waiting));
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>预约登记 - <?php echo $CONFIG['site_title']; ?></title>
    <style>
        body { 
            font-family: Arial; 
            max-width: 800px; 
            margin: 0 auto; 
            padding: 20px;
        }
        .info {
            text-align: center;
            margin: 20px 0;
            padding: 10px;
            background: #f8f8f8;
        }
        .form {
            margin: 20px 0;
        }
        .form-item {
            margin: 15px 0;
        }
        .form-item label {
            display: block;
            margin-bottom: 5px;
        }
        .form-item input {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
        }
        .btn {
            width: 100%;
            padding: 10px;
            background: #007bff;
            color: white;
            border: none;
            cursor: pointer;
        }
        .btn:disabled {
            background: #ccc;
        }
        .result {
            margin: 20px 0;
            padding: 20px;
            border: 1px solid #ddd;
            display: none;
        }
        .error {
            color: red;
            text-align: center;
            padding: 20px;
        }
    </style>
</head>
<body>
    <h1>预约登记</h1>
    
    <div class="info">
        <p>科室：<?php echo $doctor['department']; ?></p>
        <p>医生：<?php echo $doctor['name']; ?></p>
        <p>当前等待：<span id="waiting">0</span>人</p>
    </div>
    
    <div id="error" class="error" style="display:none;"></div>
    
    <div id="form" class="form" style="display:none;">
        <div class="form-item">
            <label>姓名</label>
            <input type="text" id="name" placeholder="请输入姓名">
        </div>
        <div class="form-item">
            <label>手机号</label>
            <input type="tel" id="mobile" placeholder="请输入手机号">
        </div>
        <div class="form-item">
            <label>身份证号<?php echo $CONFIG['id_card_required'] ? '' : '(选填)'; ?></label>
            <input type="text" id="id_card" placeholder="请输入身份证号">
        </div>
        <button class="btn" onclick="submitBooking()">提交预约</button>
    </div>
    
    <div id="result" class="result">
        <h3>预约成功</h3>
        <p>序号：<span id="sequence"></span></p>
        <p>核销码：<span id="verify_code"></span></p>
        <p>前面等待：<span id="ahead"></span>人</p>
        <p>预约时间：<span id="book_time"></span></p>
        <p style="color:red;">请记住核销码，叫号后15分钟内有效</p>
    </div>

    <script src="inc/js.js"></script>
    <script>
        // 检查状态
        function checkStatus() {
            ajax({
                url: 'dengji.php',
                type: 'GET',
                data: {
                    id: <?php echo $doctor_id; ?>,
                    t: <?php echo $timestamp; ?>,
                    act: 'check'
                },
                success: function(res) {
                    var data = JSON.parse(res);
                    if(data.code === 1) {
                        document.getElementById('form').style.display = 'block';
                        // ���取Cookie
                        var name = getCookie('patient_name');
                        var mobile = getCookie('patient_mobile');
                        var id_card = getCookie('patient_id_card');
                        if(name) document.getElementById('name').value = name;
                        if(mobile) document.getElementById('mobile').value = mobile;
                        if(id_card) document.getElementById('id_card').value = id_card;
                    } else {
                        document.getElementById('error').innerHTML = data.msg;
                        document.getElementById('error').style.display = 'block';
                    }
                }
            });
        }
        
        // 刷新等待人数
        function refreshCount() {
            ajax({
                url: 'dengji.php',
                type: 'GET',
                data: {
                    id: <?php echo $doctor_id; ?>,
                    act: 'count'
                },
                success: function(res) {
                    var data = JSON.parse(res);
                    if(data.code === 1) {
                        document.getElementById('waiting').textContent = data.data.count;
                    }
                }
            });
        }
        
        // 提交预约
        function submitBooking() {
            var name = document.getElementById('name').value;
            var mobile = document.getElementById('mobile').value;
            var id_card = document.getElementById('id_card').value;
            
            ajax({
                url: '?act=submit',
                type: 'POST',
                data: {
                    id: <?php echo $doctor_id; ?>,
                    act: 'submit',
                    name: name,
                    mobile: mobile,
                    id_card: id_card
                },
                success: function(res) {
                    var data = JSON.parse(res);
                    if(data.code === 1) {
                        // 保存Cookie
                        setCookie('patient_name', name, 30);
                        setCookie('patient_mobile', mobile, 30);
                        setCookie('patient_id_card', id_card, 30);
                        
                        // 显示结果
                        document.getElementById('sequence').textContent = data.data.sequence;
                        document.getElementById('verify_code').textContent = data.data.verify_code;
                        document.getElementById('ahead').textContent = data.data.waiting - 1;
                        document.getElementById('book_time').textContent = data.data.time;
                        
                        document.getElementById('form').style.display = 'none';
                        document.getElementById('result').style.display = 'block';
                    } else {
                        alert(data.msg);
                    }
                }
            });
        }
        
        // 初始检查
        checkStatus();
        refreshCount();
        
        // 定时刷新等待人数
        setInterval(refreshCount, 3000);
    </script>
</body>
</html> 